// components/uploader/upload.js
import { ASSETS_BASE_URL, UPLOAD_BASE_URL } from '@/utils/config';
Component({
    properties: {
        fileList: {
            type: Array,
            value: [],
            observer(newVal) {
                this.setData({ _fileList: newVal });
            },
        },
        maxCount: {
            type: Number,
            value: 1,
        },
        maxSize: {
            type: Number,
            value: 5,
        },
        sizeType: {
            type: Array,
            value: ['compressed'],
        },
        previewSize: {
            type: String,
            value: '160rpx',
        },
    },
    data: {
        _fileList: [],
    },
    methods: {
        /**
         * 批量上传
         * @param {Array} event.detail.file 当前读取的文件
         * @param {Function} event.detail.callback 回调函数，调用callback(false)终止文件读取
         */
        afterRead(event) {
            const { file } = event.detail;
            const { _fileList } = this.data;
            // 标记上传状态 uploading表示上传中，failed表示上传失败，done表示上传完成
            file.forEach(item => {
                item.status = 'uploading';
            });
            _fileList.push(...file);
            this.setData({ _fileList });

            // 上传
            const promiseArr = [];
            file.forEach(item => {
                const promise = this.upload(item.url);
                promiseArr.push(promise);
                promise
                    .then(url => {
                        // 上传成功
                        const { _fileList } = this.data;
                        const index = _fileList.findIndex(f => f.url === item.url);
                        item.status = 'done';
                        item.url = ASSETS_BASE_URL + url;
                        if (index > -1) {
                            _fileList[index] = item;
                        }
                        this.triggerEvent('success-uploaded', {
                            fileList: _fileList,
                            url: url,
                        });
                    })
                    .catch(() => {
                        // 上传失败
                        const { _fileList } = this.data;
                        const index = _fileList.findIndex(f => f.url === item.url);
                        item.status = 'failed';
                        if (index > -1) {
                            _fileList[index] = item;
                        }
                        this.setData({ _fileList });
                    });
            });
            // 上传失败提示
            Promise.all(promiseArr).catch(() => {
                wx.showToast({
                    title: '上传失败,请稍后再试',
                    icon: 'none',
                });
            });
        },
        /**
         * 单资源上传
         * @param {String} url 资源本地路径
         * @return {Promise} promise
         */
        upload(url) {
            return new Promise((resolve, reject) => {
                wx.uploadFile({
                    url: UPLOAD_BASE_URL,
                    filePath: url,
                    name: 'file',
                    success: res => {
                        if (res.statusCode === 200) {
                            const url = JSON.parse(res.data).data.file_path;
                            resolve(url);
                        } else {
                            reject();
                        }
                    },
                    fail: () => {
                        reject();
                    },
                });
            });
        },
        // 删除图片
        deleteImg(e) {
            const { index } = e.detail;
            const { _fileList } = this.data;
            const status = _fileList[index].status;
            _fileList.splice(index, 1);

            if (status === 'done') {
                this.triggerEvent('after-delete', {
                    fileList: _fileList,
                    index,
                });
            } else {
                this.setData({ _fileList });
            }
        },
        // 文件超出大小限制
        overSize() {
            wx.showToast({
                title: `请上传小于${this.properties.maxSize}M的图片`,
                icon: 'none',
            });
        },
    },
});
